// pages/login/login.js
const app = getApp(),
  core = require('../../utils/core'),
  chatIM = require('../../utils/websocket.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nav: 0,
    wx_account: null,
	mobile: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let page = this;
    page.setData({
	  wx_account: app.getWxAccount(),
	});
	app.wxLogin(function(){
		chatIM.connectSocket();
		if (getCurrentPages().length > 1) {
			wx.navigateBack({
			  delta: 2,
			})
		  } else {
			wx.switchTab({
			  url: '/pages/user_center/user_center',
			})
		  }
	});
    app.eventBus.on(app.Events.WxAccountUpdate, page.eventOnWxAccountUpdate, page);
  },

  /**
   * 手机号
   */
  getPhoneNumber(e) {
    var that = this;
	let version = wx.getSystemInfoSync().SDKVersion;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      if (that.compareVersion(version, '2.21.2') >= 0) {
        that.phoneNumber(that, {
          code: e.detail.code
        })
      } else {
        that.phoneNumber(that, {
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        })
      }
    } else {
      console.log("用户点击了拒绝")
    }
  },

  phoneNumber(that, data) {
    let wxAccount = app.getWxAccount();
	data['third_id'] = wxAccount.third_id;
    core.post({
      url: 'xilujob.user/wxNumberEncrypted',
      data: data,
      success: (ret, response) => {
        wxAccount['binding'] = 1;

        let userinfo = ret.data.userinfo;
        app.setUserinfo(userinfo);

        core.setCache('wx_account', wxAccount);
        that.setData({
          wx_account: wxAccount
        });

        app.eventBus.emit(app.Events.WxAccountUpdate, wxAccount);

		app.eventBus.emit(app.Events.UserLogin, userinfo);
		chatIM.connectSocket();
        if (getCurrentPages().length > 1) {
          wx.navigateBack({
            delta: 2,
          })
        } else {
          wx.switchTab({
            url: '/pages/user_center/user_center',
          })
        }

      },
      fail: (ret, response) => {
        //失败，重试
        wx.showToast({
          'title': "获取失败",
          icon: "none"
        })
        return false;
      }
    });

  },


  //版本比较
  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }

    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])

      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }

    return 0
  },
  nologin: function () {
    wx.navigateBack({
      delta: 1,
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.eventBus.off(app.Events.UserLogin, this.eventOnUserLogin);
  },

  eventOnWxAccountUpdate: function (wxAccount) {
    this.setData({
      wx_account: wxAccount
    });
  }


});
